<?php
namespace Home\Controller;
use Think\Controller;
use Think\Page;
class SellController extends CommonController {
	/*
		匹配E积分记录
	*/
	public function matchEpoint(){
		$this -> assign('title','匹配E积分');
		$Marketmod = M('market');
		$Parammod = M('param');
		//获取该用户所有出售E积分的数据
		$Epointres = $Marketmod -> where('sell_user_id= "%d" and change_type = "option_num" ',$_SESSION['users']['user_id'])->order('sell_time desc')->select();
		$res = $Parammod -> find() ;
		// 获取坐标的图
		$mod = M('k_log');
		//增长轴
		$k_money = $mod -> field('k_money')->select();
		 $qdata = "[";
		$count = count($k_money);		
		    $i=0;
		    foreach($k_money as $v){
		        if($i <=$count-2){
		            $qdata .=$v['k_money'].',';
		        }else{
		            $qdata .=$v['k_money'];
		        }
		       $i+=1;
		    }
    	$qdata .=']';
    	//时间轴
    	$k_datetime = $mod -> field('k_datetime')->select();
		 $tdata = "[";
		$count = count($k_datetime);		
		    $i=0;
		    foreach($k_datetime as $v){
		        if($i <=$count-2){
		            $tdata .=$v['k_datetime'].',';
		        }else{
		            $tdata .=$v['k_datetime'];
		        }
		       $i+=1;
		    }
    	$tdata .=']';
    	//查询用户信息
    	$user = M('users') -> where('user_id=%d',[$_SESSION['users']['user_id']]) -> find();
    	$this -> assign('user',$user);
        $this->assign('qdata',$qdata);
        $this->assign('tdata',$tdata);
       
		$this -> assign('res',$res);
		
		$this -> display('');
	}

		//出售e积分
	public function sellEpoint(){
			$this -> assign('title','匹配E积分');
			
				$Marketmod = M('market');
				$Parammod = M('param');
				//获取该用户所有出售E积分的数据
				$Epointres = $Marketmod -> where('sell_user_id= "%d" and change_type = "option_num" ',$_SESSION['users']['user_id'])->order('sell_time desc')->select();
				$res = $Parammod -> find() ;
				// 获取坐标的图
				$mod = M('k_log');
				//增长轴
				$k_money = $mod -> field('k_money')->select();
				 $qdata = "[";
				$count = count($k_money);		
				    $i=0;
				    foreach($k_money as $v){
				        if($i <=$count-2){
				            $qdata .=$v['k_money'].',';
				        }else{
				            $qdata .=$v['k_money'];
				        }
				       $i+=1;
				    }
		    	$qdata .=']';
		    	//时间轴
		    	$k_datetime = $mod -> field('k_datetime')->select();
				 $tdata = "[";
				$count = count($k_datetime);		
				    $i=0;
				    foreach($k_datetime as $v){
				        if($i <=$count-2){
				            $tdata .=$v['k_datetime'].',';
				        }else{
				            $tdata .=$v['k_datetime'];
				        }
				       $i+=1;
				    }
		    	$tdata .=']';
    	//查询用户信息
    	$user = M('users') -> where('user_id=%d',[$_SESSION['users']['user_id']]) -> find();
    
    	$this -> assign('user',$user);
        $this->assign('qdata',$qdata);
        $this->assign('tdata',$tdata);
		$this -> assign('res',$res);
		
		$this -> display('');
	}


	/*
		E积分成交记录
	*/

	public function successEpoint(){
		$this -> assign('title','E积分成交记录');
		//搜索卖出记录
		$logmod = M('market');
		$data['sell_user_id'] = array('eq',$_SESSION['users']['user_id']);
		$data['change_type'] = array('eq','option_num') ;
		$data['status'] = array('eq','3') ;
		//配置分页信息
		$endtime = strtotime(I('get.end'));
		$starttime = strtotime(I('get.start'));	
				if(!empty($endtime)&&!empty($starttime)){																					
						$data['sell_time'] = array('egt',$starttime);
			 			$page = new Page($logmod -> where($data)->count(),3);			 			
			 			$page->setConfig('prev','上一页');
			 			$page->setConfig('next','下一页');			 		
						//分页链接
						$url = $page->show();
						$this -> assign('url',$url);		
						$epoint = $logmod -> where($data)->where('sell_time<='.$endtime)->order('sell_time desc')->limit($page->firstRow,$page->listRows)->select();		
				}else{
						$page = new Page($logmod -> where($data)->count(),3);			 			
			 			$page->setConfig('prev','上一页');
			 			$page->setConfig('next','下一页');			
			 		
						//分页链接
						$url = $page->show();		
					    $this -> assign('url',$url);
					    $epoint = $logmod -> where($data)->order('sell_time desc')->limit($page->firstRow,$page->listRows)->select();		
				}
		//计算出各种钱
		$parammod = M('param');
		$param = $parammod -> field('param4,param5,param6,param7') -> where('id = 1') -> find();
		foreach($epoint as $k=>$v){
				$epoint[$k]['change_time'] = date('Y-m-d H:i:s',$v['sell_time']);
				$epoint[$k]['amount_my'] = $v['sell_num']*$v['sell_money'];
				$epoint[$k]['koushui'] = number_format($v['sell_num']*$param['param4']/100,2);
				$epoint[$k]['shangcheng'] = number_format($v['sell_num']*(100-$param['param4'])/100*$param['param7']/100,2);
				$epoint[$k]['xianjing'] = number_format($v['sell_num']*(100-$param['param4'])/100*$param['param6']/100*$v['sell_money'],2);
				$epoint[$k]['ejifen'] = number_format($v['sell_num']*(100-$param['param4'])/100*$param['param5']/100,2);
		}
		$this -> assign('epoint',$epoint);
		$this -> display('');


	}

	//现金积分成交记录
	public function  successCashpoint(){
		$this -> assign('title','现金积分成交记录');
		$mod = M('market');		
		$data['status'] = array('eq','3');
		$data['change_type'] = array('eq','user_money1');
		$cashmod = $mod -> where($data)->where('sell_user_id='.$_SESSION['users']['user_id'].' or buy_user_id = '.$_SESSION['users']['user_id'])->select();
		
		foreach($cashmod as $k=>$v){
			$cashmod[$k]['cashnum']=$v['sell_money']*$v['sell_num'];
		}
		$this -> assign('cash',$cashmod);
		$this -> assign('id',$_SESSION['users']['user_id']);		
		$this -> display('');
	}

	//出售现金积分
	public function sellmoney(){
		//获取当前用户的现金积分
		$money1 = M('users') -> field('user_money1') -> where('user_id=%d',[$_SESSION['users']['user_id']]) -> find();
		//获取当前市价
		$param = M('param') -> field('param11') -> where('id=%d',[1]) -> find();
		// dump($param);die;
		//获取出售中的现金积分
		$money = M('market') -> field('mk_id,sell_time,content,sell_num,status') -> where('sell_user_id=%d and change_type="%s"',[$_SESSION['users']['user_id'],'user_money1']) -> select();
		$count = M('market')-> where('sell_user_id=%d and change_type="%s"',[$_SESSION['users']['user_id'],'user_money1']) -> count();
		$this -> assign('count',$count);
		$this -> assign('money',$money);
		$this -> assign('param11',$param['param11']);
		// dump($money1['user_money1']);die;
		$this -> assign('money1',$money1['user_money1']);
		$this -> display();
	}

	//出售现金操作
	public function actsellmoney(){
		//判断安全码
		$res = M('users') -> field('user_id,repassword') -> where('user_id=%d',[$_SESSION['users']['user_id']]) -> find();
		if(md5(I('post.repassword')) == $res['repassword']){
			M() -> startTrans();
			//改用户现金积分
			$res1 = M() -> execute('update zx_users set user_money1 = user_money1 -'.I('POST.sell_points').' where user_id = '.$_SESSION['users']['user_id']);
			//获取当前市价
			$param1 = M('param') -> field('param11') -> where('id=%d',[1]) -> find();
			//加入到市场日志中
			$data = ['sell_user_id'=>$_SESSION['users']['user_id'],'sell_user_name'=>$_SESSION['users']['user_name'],
			'change_type'=>'user_money1','sell_num'=>I('post.sell_points'),'sell_money'=>$param1['param11'],
			'sell_time'=>time(),'content'=>'现金积分','status'=>0];
			$res2 = M('market') -> data($data) -> add();
			if($res1 && $res2){
				M() -> commit();
				$this -> success('出售成功，等候购买');
			}else{
				M() -> rollback();
				$this -> error('出售失败');
			}
		}else{
			$this -> error('安全码错误');
		}
	}

	//发货现金积分
	public function send(){
		//查询该比交易的信息
		$market = M('market') -> field('sell_num,sell_user_id,buy_user_id') -> where('mk_id=%d',[I('get.mk')]) -> find();
		M() -> startTrans();
		$res1 = M() -> execute('update zx_users set user_money1 = user_money1 + '.$market['sell_num'].' where user_id = %d',$market['buy_user_id']);
		// M() -> _SQL();die;
		// $res2 = M() -> execute('update zx_users set user_money1 = user_money1 - '.$market['sell_num'].' where user_id = %d',$market['sell_user_id']);
		$res3 = M('market') -> data(['status'=>3,'action_time'=>time()]) -> where('mk_id=%d',[I('get.mk')]) -> save();
		if($res1 && $res3){
			M() -> commit();
			$this -> success('交易成功');
		}else{
			M() -> rollback();
			$this -> error('交易失败');
		}
	}

	//购买现金积分
	public function buymoney(){
		$money = M('market') -> field('mk_id,sell_user_id,sell_user_name,content,sell_num,sell_money,status,sell_time') -> where('status=%d and sell_user_id<>"%s"',[0,$_SESSION['users']['user_id']]) -> select();
		$money2 = M('market') -> field('mk_id,sell_user_id,sell_user_name,content,sell_num,sell_money,status,sell_time') ->  where('status<>%d and buy_user_id="%f" and sell_user_id<>"%s"',[0,$_SESSION['users']['user_id'],$_SESSION['users']['user_id']]) -> select();
		// echo M('market') -> _SQL();die;
		// dump($money2);die;
		$count = M('market') ->  where('status<>%d and buy_user_id="%f" and sell_user_id<>"%s"',[0,$_SESSION['users']['user_id'],$_SESSION['users']['user_id']]) -> count(); 
		// dump($money);
		// dump($money2);die;
		$this -> assign('money2',$money2);
		// dump($money2);die;
		$this -> assign('count',$count);
		$this -> assign('money',$money);
		$this -> display();
	}

	//购买现金积分操作
	public function buy(){
		$market = M('market') -> field('buy_time,status') -> where('mk_id=%d',[I('get.mk')]) -> find();
		if($market['status'] == 6){
			$this -> error('该交易已撤销');
		}
		M() -> startTrans();
		if($market['buy_time']>0){
			$this -> error('对不起，该现金积分已被购买');
		}else{
			$res = M('market') -> data(['buy_time'=>time(),'status'=>1,'buy_user_name'=>$_SESSION['users']['user_name'],'buy_user_id'=>$_SESSION['users']['user_id']]) -> where('mk_id=%d',[I('get.mk')]) -> save();
			if($res){
				M() -> commit();
				$this -> success('购买成功');
			}else{
				M() -> rollback();
				$this -> error('购买失败');
			}
		}
	}

	//付款操作
	public function fukuan(){
		$res = M('market') -> data(['pay_time'=>time(),'status'=>2]) -> where('mk_id=%d',[I('get.mk')]) -> save();
		if($res>0){
			$this -> success('付款成功，请等待对方发货');
		}else{
			$this -> error('付款失败');
		}
	}

	//撤销
	public function cancel(){
		M() -> startTrans();
		$res = M('market') -> data(['status'=>6]) -> where('mk_id',[I('get.mk')]) -> save();
		$res2 = M('market') -> field('sell_num,sell_user_id') -> where('mk_id=%d',[I('get.mk')]) -> find();
		// dump($res2);die;
		$res3 = M() -> execute('update zx_users set user_money1 = user_money1 + '.$res2['sell_num'].' where user_id = %d',$res2['sell_user_id']);
		if($res && $res2 && $res3){
			M() -> commit();
			$this -> success('撤销成功，已将积分返回');
		}else{
			M() -> rollback();
			$this -> error('撤销失败');
		}
	}

	//出售E积分操作
	public function sellejf(){
		if(I('post.mobile_code')==$_SESSION['mobile']['code']){
			if(I('post.sell_option_num')<I('post.sell_num')){
				$this -> error('你出售的数量超出课出售最大值');
			}else{
				$param = M('param') -> field('param1') -> where('id=%d',[1]) -> find();
				$user = $_SESSION['users'];
				if(md5(I('post.repassword')) == $_SESSION['users']['repassword']){
					if(I('post.param1')>=I('post.maxsell')){
						$this -> error('已大于最大出售上涨值，您不能出售');
					}else{
						M() -> startTrans();
						$data = ['sell_user_name'=>$user['user_name'],'sell_user_id'=>$user['user_id'],'change_type'=>'option_num','sell_num'=>I('post.sell_num'),'sell_money'=>$param['param1'],'sell_time'=>time(),'buy_time'=>time(),'action_time'=>time(),'content'=>'E积分'];
						$res = M('market') -> data($data) -> add();
						$res2 = M() -> execute('update zx_users set option_num2 = option_num2 + '.I('post.sell_num').', option_num = option_num - '.I('post.sell_num').',sell_option_num = sell_option_num - '.I('post.sell_num').' where user_id = %d',$user['user_id']);
						if($res && $res2){
							M() -> commit();
							$this -> success('出售成功');
						}else{
							M() -> rollback();
							$this -> error('出售失败');
						}
					}
				}else{
					$this -> error('安全码不正确');
				}
			}

		}else{
			$this -> error('验证码不正确');
		}
		
		
	}

	//交易信息
	public function infomation(){
		$buy = M('market') -> field('buy_user_id') -> where('mk_id=%d',[I('get.aa')]) -> find();
		$res = M('users') -> field('mobile_phone,cardno,zhifubao,weixin,user_id,user_name,bank_name,mainbank,true_name') -> where('user_id=%s',[$buy['buy_user_id']]) -> find();
		$this -> assign('res',$res);
		$this -> display();
	}

	public function infomation1(){
		$buy = M('market') -> field('sell_user_id') -> where('mk_id=%d',[I('get.aa')]) -> find();
		// dump($buy);die;
		$res = M('users') -> field('mobile_phone,cardno,zhifubao,weixin,user_id,user_name,bank_name,mainbank,true_name') -> where('user_id=%s',[$buy['sell_user_id']]) -> find();
		$this -> assign('res',$res);
		$this -> display('sell/infomation');
	}
		//处理验证码
	
	public function phoneAjax(){
		if(I('post.code')==1){			
				$_SESSION['mobile']['code'] = rand('111111','999999');
				$_SESSION['mobile']['mobile'] =  $_SESSION['users']['mobile_phone'];				
				$_SESSION['mobile']['content']=",您的短信验证码为".$_SESSION['mobile']['code']."，仅用于修改密码、卖出现金积分操作，短信验证码的有效时间为5分钟，使用后即作废。";
			
			$this -> send_msg();
			
		}else{
			echo  '2';
		}

	}
//短信接口
		//封装好的发送短信接口
	public function send_msg(){
				   
					//接口账号
					$uid = 'dong354698601';

					//登录密码
					$pwd = 'dong6395175346';

					/**
					* 实例化接口
					* 
					* @param string $uid 接口账号
					* @param string $pwd 接口密码					*/
				
					$api = new \Org\Util\Smsapi($uid,$pwd);

					$mobile = $_SESSION['mobile']['mobile'];

					//短信内容参数
					$contentParam = array(
						'code'		=> $_SESSION['mobile']['code'],
						'username'	=> $_SESSION['mobile']['content']
						);

					//变量模板ID
					$template = '397816';

					//发送变量模板短信
					$result = $api->send($mobile,$contentParam,$template);

					if($result['stat']=='100')
					{
						echo '发送成功';
					}
					else
					{
						echo '发送失败:'.$result['stat'].'('.$result['message'].')';
					}

		}











}